<template>
	<d2-container>
		<div class="order-details">
			<div class="order-number">
				<span>订单编号：{{ orderDetails.orderNo }}</span>&nbsp;&nbsp;
				<span>下单时间：{{ orderDetails.createTime | forDate}}</span>&nbsp;&nbsp;
				<span>会员账号：{{ orderDetails.userPhone }}</span>&nbsp;&nbsp;
				<span v-if="orderDetails.orderType == 2"> 提货码：{{ orderDetails.pickupNo }}</span>&nbsp;&nbsp;
			</div>

			<div class="order-details-info">
				<el-table :data="tableData" stripe border style="width: 100%">
					<el-table-column label="订单状态" width="120">
						<template slot-scope="scope">
							<div class="table-list">
								<el-image v-if="scope.row.orderStatus === 2 && (scope.row.afterSalesStatus==0||scope.row.afterSalesStatus==5)" style="width: 80px; height: 80px" :src="require('@/assets/orderStatus/success.png')" ></el-image>
								<el-image v-if="scope.row.orderStatus === 2 && (scope.row.afterSalesStatus==1||scope.row.afterSalesStatus==3)" style="width: 80px; height: 80px" :src="require('@/assets/orderStatus/success.png')" ></el-image>
								<el-image v-if="scope.row.orderStatus === 2 && (scope.row.afterSalesStatus==2 ||scope.row.afterSalesStatus==4)" style="width: 80px; height: 80px" :src="require('@/assets/orderStatus/close.png')" ></el-image>
								<el-image v-if="scope.row.orderStatus === 3" style="width: 80px; height: 80px" :src="require('@/assets/orderStatus/close.png')" ></el-image>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="订单信息">
						<template slot-scope="scope">
							<div class="table-list">
								<p>订单类型：{{scope.row.orderType === 1 ? '零售订单' : scope.row.orderType === 2 ? '商城自提' : '商城物流'}}</p>
								<p>订单主状态：
									{{scope.row.orderStatus==0?"初始":""}}
									{{scope.row.orderStatus==1?"待付款":""}}
									{{scope.row.orderStatus==2&&scope.row.afterSalesStatus!=4?"交易成功（已付款）":""}}
									{{scope.row.orderStatus==3?"交易关闭（取消订单）":""}}
									{{scope.row.orderStatus==2&&scope.row.afterSalesStatus==4?"交易关闭（售后退款）":""}}
								</p>
								<p>售后状态：
									{{scope.row.afterSalesStatus==0?"无售后":""}}
									{{scope.row.afterSalesStatus==1?"部分退款中":""}}
									{{scope.row.afterSalesStatus==2?"全部退款中":""}}
									{{scope.row.afterSalesStatus==3?"部分退款成功":""}}
									{{scope.row.afterSalesStatus==4?"全部退款成功":""}}
									{{scope.row.afterSalesStatus==5?"已撤销退款":""}}
								</p>
								<p>支付方式：{{scope.row.payType === 1 ? '账户支付' : scope.row.payType === 2 ? '现金支付' : scope.row.payType === 3 ? '通联支付' : '未付款'}}</p>
								<p>交易流水：{{scope.row.transactionId ? scope.row.allinpayOrderNo : '-'}}</p>
								<p>付款时间：{{scope.row.payTime | forDate}}</p>
								<p>小票打印时间：{{scope.row.printTime | forDate}}</p>
								<p>小票编号：{{scope.row.ticketNo}}</p>
							</div>
						</template>
					</el-table-column>
					<el-table-column  v-if="orderDetails.afterSalesStatus == 3 ||
					                        orderDetails.afterSalesStatus == 4" label="退款退货">
						<template slot-scope="scope">
							<div class="table-list">
								<p>售后类型：{{scope.row.afterSalesType==3?"退款退货":"仅退款（无需退货）"}}</p>
								<p>售后状态：{{scope.row.afterSalesStatus==3?"已部分退款":"已全部退款"}}</p>
								<p>申请时间：{{scope.row.afterSalesTime | forDate}}</p>
								<p>退款路径：{{scope.row.refundPath==0?"原路退回":"线下退款"}}</p>
								<p>退款方式：{{scope.row.refundType==1?"支付宝":scope.row.refundType==2?"微信":scope.row.refundType==3?"通联":"现金"}}</p>
							    <p>退款流水号(交易号)：{{scope.row.refundFlowNo}}</p>
								<p>退款金额：￥{{scope.row.refundAmount}}</p>
								<p>退券金额：￥{{scope.row.refundCouponAmount}}</p>
								<p>退款时间：{{scope.row.refundTime | forDate}}</p>
								<p>退款人：{{scope.row.refunder}}</p>
								<p>退货退款理由：{{scope.row.reason==0?"不想要了":scope.row.reason==1?"过期商品":scope.row.reason==2?"包装破损":"其他"}}</p>
								<p>退货退款备注：{{scope.row.refundRemark}}</p>
							</div>
						</template>
					</el-table-column>
					<el-table-column  v-if="orderDetails.orderType == 2" label="提货信息">
						<template slot-scope="scope">
							<div class="table-list">
								<p>提货门店：{{scope.row.pickupName}}</p>
								<p>门店地址：{{scope.row.pickupAddress}}</p>
								<p>门店电话{{scope.row.pickupPhone}}</p>
								<p>小门店营业时间：{{scope.row.pickupBusinessHours}}</p>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<div class="order-sku-list">
				<el-table :data="detailsTableData" stripe border style="width: 100%" @selection-change="handleSelectionChange">
					<el-table-column label="订单明细">
						<el-table-column type="selection" width="55"></el-table-column>
						<el-table-column label="商品信息" width="400">
							<template slot-scope="scope">
								<div class="sku-info">
									<div class="sku-image">
										<el-image style="width: 80px; height: 80px;" :src="scope.row.thumbImage">
										</el-image>
									</div>
									<div class="sku-details">
										<h3>{{scope.row.productName}}</h3>
										<p>{{scope.row.productSkuName}}</p>
									</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="商品条码" prop="productBarCode" width="200"></el-table-column>
						<el-table-column label="数量" prop="quantity" ></el-table-column>
                        <el-table-column label="已退货/退款数量" prop="quantityRefunded" ></el-table-column>
                        <el-table-column label="可退货/退款数量" prop="refundableQuantity" >
						    <template slot-scope="scope">
								{{scope.row.quantity - scope.row.quantityRefunded}}
							</template>
						</el-table-column>
						<el-table-column label="本次退货/退款数量" prop="refundQuantity" width="180">
							<template slot-scope="scope">
								<el-input-number v-model="scope.row.refundQuantity" size="small" :min="0" :max="scope.row.avilableRefundQuantity">
								</el-input-number>
							</template>
						</el-table-column>
						<el-table-column label="单位" prop="unitName" ></el-table-column>
						<el-table-column label="零售单价" >
							<template slot-scope="scope">
								¥{{scope.row.price}}
							</template>
						</el-table-column>
						<el-table-column v-if="orderDetails.isMemberPay ==1" label="会员单价" >
							<template slot-scope="scope">
								¥{{scope.row.memberPrice}}
							</template>
						</el-table-column>
						<el-table-column v-if="orderDetails.isMemberPay ==1" label="消费券" >
							<template slot-scope="scope">
								¥{{scope.row.memberCoupon}}
							</template>
						</el-table-column>
						<el-table-column v-if="orderDetails.isMemberPay ==1" label="消费券小计">
							<template slot-scope="scope">
								¥{{scope.row.couponAmountSubtotal}}
							</template>
						</el-table-column>
						<el-table-column v-if="orderDetails.isMemberPay ==1" label="金额小计" >
							<template slot-scope="scope">
								¥{{scope.row.memberPriceSubtotal}}
							</template>
						</el-table-column>
						<el-table-column v-if="orderDetails.isMemberPay ==0" label="金额小计" >
							<template slot-scope="scope">
								¥{{scope.row.orderAmount}}
							</template>
						</el-table-column>
					</el-table-column>
				</el-table>

				<div class="sku-summary">
					<div class="sku-summary-content">
						<p>
							<span>商品总金额：</span><span>¥{{orderDetails.orderAmount}}</span>
						</p>
						<p v-if="orderDetails.isMemberPay ==1" >
							<span>消费券合计：</span><span>¥{{orderDetails.couponAmount}}</span>
						</p>
						<p>
							<span>优惠金额：</span><span>¥{{orderDetails.discountAmount}}</span>
						</p>
						<p>
							<span>物流费：</span><span>¥{{orderDetails.logisticsFee}}</span>
						</p>
						<p>
							<span>服务费：</span><span>¥{{orderDetails.serviceFee}}</span>
						</p>
						<p>
							<span>应支付金额：</span><span>¥{{orderDetails.payableAmount}}</span>
						</p>
						<p>
							<span>实际支付金额：</span><span class="sku-summary-text">¥{{orderDetails.payAmount}}</span>
						</p>
						<p>
							<span>找零金额：</span><span class="sku-summary-text">¥{{orderDetails.changeAmount}}</span>
						</p>
						<p>
							<span>实付消费券金额：</span><span class="sku-summary-text">¥{{orderDetails.couponAmountPay}}</span>
						</p>
					</div>
				</div>
			</div>

		</div>
		<div class="form-afterSale">
			<h3>退货退款信息</h3>
			<el-form ref="submitForm" :model="submitForm" :rules="submitFormRules" class="header-area" label-width="110px" style="height:auto">
				<el-row>
					<el-col :span="8">
						<el-form-item label="售后类型" prop="afterSalesType">
							<el-select v-model="submitForm.afterSalesType" placeholder="请选择" style="width: 100%;">
								<el-option label="退款退货" value="1"></el-option>
								<el-option label="仅退款（无需退货）" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="退款路径" prop="refundPath">
							<el-select v-model="submitForm.refundPath" placeholder="请选择退款路径" style="width: 100%;">
								<el-option v-if="orderDetails.payType == 1 || orderDetails.payType == 2 || orderDetails.payType == 3" label="原路退回" value="0"></el-option>
								<el-option v-if="orderDetails.payType == 3" label="线下退款" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="退货退款理由" prop="refundReason">
							<el-select v-model="submitForm.refundReason" placeholder="请选择" style="width: 100%;margin-bottom: 20px;">
								<el-option label="不想要了" value="0"></el-option>
								<el-option label="过期商品" value="1"></el-option>
								<el-option label="包装破损" value="2"></el-option>
								<el-option label="其它" value="3"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="退款方式" prop="refundType">
							<el-select v-model="submitForm.refundType" placeholder="请选择" style="width: 100%;margin-bottom: 20px;">
								<el-option v-if="orderDetails.payType != 2" label="无" value="0"></el-option>
								<el-option v-if="orderDetails.payType == 3" label="支付宝" value="1"></el-option>
								<el-option v-if="orderDetails.payType == 3" label="微信" value="2"></el-option>
								<el-option v-if="orderDetails.payType == 3" label="通联" value="3"></el-option>
								<el-option v-if="orderDetails.payType == 2" label="现金" value="4"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8" v-if="orderDetails.payType == 3">
						<el-form-item label="退款流水号" prop="refundFlowNo">
							<el-input type="text" v-model="submitForm.refundFlowNo" placeholder="请输入退款流水号（交易号）" style="width: 100%;margin-bottom: 20px;"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="orderDetails.payType == 3">
						<el-form-item label="退款账号" prop="refundAccount">
							<el-input type="text" v-model="submitForm.refundAccount" placeholder="请输入退款账号" style="width: 100%;margin-bottom: 20px;"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="其它说明" prop="remark">
							<el-input type="textarea" v-model="submitForm.remark" placeholder="请输入其它说明" style="width: 100%;margin-bottom: 20px;"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="orderDetails.payType == 3">
						<el-form-item label="联系电话" prop="contactPhone">
							<el-input type="text" v-model="submitForm.contactPhone" placeholder="请输入联系电话" style="width: 100%;margin-bottom: 20px;"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="24">
					    <el-form-item>
                            <div class="form-submit">
						<el-button v-if="showRefundBut" @click="confirmRefund('submitForm')" class="form-submit-btn" type="primary">确认申请退款</el-button>
						<el-button class="form-cancle-btn" @click="closePage">返回</el-button>
					        </div>
                        </el-form-item>
					</el-col>
				</el-row>

			</el-form>
		</div>
	</d2-container>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { queryOrderDetailByOrderId, OrderRefundApply } from '@api/order/order'
import dayjs from 'dayjs'
import { ossDomain } from '@api/sys.common'
export default {
  data () {
    return {
      orderId: '',
      orderDetails: {},
      tableData: [],
	  detailsTableData: [],
	  showRefundBut: false,
	  multipleSelection: [],
	  submitForm: {
        orderId: '',
        afterSalesType: '',
        refundFlowNo: '',
        refundReason: '',
        remark: '',
        refundType: '',
        refundPath: '',
        refundAccount: '',
        contactPhone: '',
        selectDetails: []
	  },
	  submitFormRules: {
        afterSalesType: [{ required: true, message: '请选择售后类型' }],
        refundPath: [{ required: true, message: '请选择退款路径' }],
        refundReason: [{ required: true, message: '请选择退货退款理由' }],
        refundType: [{ required: true, message: '请选择退款方式' }]
      }
    }
  },
  computed: {
	  ...mapState('d2admin/page', ['opened', 'current']) // 用户获取当前页面的地址，用于关闭
  },
  filters: {
    forDate: (val) => {
      let formatTime = ''
      formatTime = val == null ? '' : dayjs(val).format('YYYY-MM-DD HH:mm:ss')
      return formatTime
    }
  },
  methods: {
    ...mapActions('d2admin/page', ['close']),
    getDetails () { // 获取详情
      queryOrderDetailByOrderId({ orderId: this.orderId }).then(res => {
        this.orderDetails = res.data
        this.tableData.push(res.data)

        res.data.details.forEach(item => {
          if (item.productType == 0 && item.quantityRefunded != item.quantity) {
            item.thumbImage = ossDomain + item.thumbImage
		        this.$set(item, 'refundQuantity', 0)
		        this.$set(item, 'avilableRefundQuantity', item.quantity - item.quantityRefunded)
			    this.detailsTableData.push(item)
		    }
        })

        // 无售后或者售后申请被撤销
        if (this.orderDetails.afterSalesStatus == 0 || this.orderDetails.afterSalesStatus == 5 || this.orderDetails.afterSalesStatus == 3) {
          this.showRefundBut = true
        }
      })
    },
    closePage () { // 关闭当前窗口
	  let tagName = this.current
	  this.close({ tagName })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    confirmRefund (formName) {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          message: '请选择需要退款的订单明细',
          type: 'warning'
        })
        return
      }
      let selectDetails = this.multipleSelection

      let refundDetails = []
      for (var i = 0, len = selectDetails.length; i < len; i++) {
        var obj = {}
        obj.orderId = selectDetails[i].orderId
        obj.id = selectDetails[i].id
        obj.refundQuantity = selectDetails[i].refundQuantity

        if (obj.refundQuantity <= 0) {
          this.$message({
            message: '请选择退款数量',
            type: 'warning'
          })
          return
        }

        // 可退数量
        var refundableQuantity = Number(obj.quantity) - Number(obj.quantityRefunded)
        if (obj.refundQuantity > refundableQuantity) {
          this.$message({
            message: '请选择退款数量',
            type: 'warning'
          })
          return
        }

        refundDetails[i] = obj
      }

      this.submitForm.selectDetails = refundDetails

      let form = this.objDeepCopy(this.submitForm)

      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('确认提交退货/退款申请吗？').then(_ => {
            this.loading = true
            OrderRefundApply(form).then(res => {
			  if (res.code = '000000') {
                this.$message({
                  message: '订单退货/退款申请提交成功',
                  type: 'success'
                })
                this.closePage()
                this.showRefundBut = false
			  } else {
                this.$message({ message: res.message, type: 'error' })
			  }
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          })
        }
      })
    },

    // 对象深拷贝
    objDeepCopy (source) {
	    let sourceCopy = source instanceof Array ? [] : {}
	    for (let item in source) {
	        sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item]
	    }
	    return sourceCopy
    }
  },
  created () {
    this.orderId = sessionStorage.getItem('orderIdApply')
    this.submitForm.orderId = this.orderId
    this.getDetails()
  }
}
</script>

<style lang="scss" scoped>
.order-details {
	padding: 20px;
	.order-number {
		width: 100%;
		height: 60px;
		align-items: center;
		display: flex;
		border:#666 1px
		span {
			font-size: 14px;
			color: #333;
			margin: 30px 30px 30px 30px;
		}
	}

	.order-progress {
		width: 100%;
		align-items: center;
		display: flex;
		padding: 50px 0;
		.order-status {
			width: 250px;
			text-align: center;
			flex: 0 0 100px;
			h3 {
				font-size: 24px;
				color: #333;
			}
			p {
				font-size: 14px;
				color: #999;
				margin-top: 10px;
			}
		}
		.order-progress-bar {
			flex: 1 1 auto;
		}
	}

	.order-details-info {
		width: 100%;
		.table-list {
			p {
				font-size: 14px;
				color: #666;
				margin: 3px 0;
			}
		}
	}

	.order-sku-list {
		width: 100%;
		margin-top: 30px;
		.sku-info {
			width: 100%;
			display: flex;
			.sku-image {
				width: 80px;
				height: 80px;
				flex: 0 0 80px;
			}
			.sku-details {
				flex: 1 1 auto;
				h3 {
					font-size: 14px;
					color: #333;
					padding-left: 30px;
				}
				p {
					font-size: 14px;
					color: #999;
					margin-top: 4px;
					padding-left: 30px;
				}
			}
		}
		.sku-summary {
			border: #ebeef5 1px solid;
			border-top: none;
			justify-content: flex-end;
			display: flex;
			padding: 20px;
			.sku-summary-content {
				width: 240px;
				p {
					width: 100%;
					font-size: 14px;
					color: #333;
					justify-content: space-between;
					display: flex;
					margin: 5px 0;
				}
				span {
					font-size: 14px;
				}
				span.sku-summary-text {
					font-size: 18px;
					font-weight: bold;
					color: #ff5642;
				}
			}
		}
	}
}

::v-deep .el-table thead.is-group th {
	background: #fff!important;
}
.warning-text {
	color: #ff5642;
}
.success-text {
	color: #1aa57b;
}
</style>
